﻿using CqCore.Exception;
using CqCore.UploadService;
using CqCore.UploadService.Base;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using UploadService.Compress;
using UploadService.Extensions;
using UploadService.Option;

namespace UploadService
{
    public class UploadService : IUploadService
    {
        private readonly ImageServiceOption option;

        public UploadService(ImageServiceOption option)
        {
            this.option = option;
        }

        public async Task<string> DomianUpload(IFormFile file, IFileUploader uploader)
        {
            try
            {
                //验证上传的文件
                string reason;
                using (var strem = file.OpenReadStream())
                {
                    if (!uploader.Validate(file.FileName, strem, out reason))
                    {
                        throw new Exception(reason+ BadRequstKey.Key);
                    }
                }
                //保存文件到指定文件夹  
                var newRandomCode = new Random().Next(1000);
                var fileName = string.Format("{0}_{1}{2}", DateTime.Now.ToString("yyyyMMddhhmmss"), newRandomCode, Path.GetExtension(file.FileName));
                var fullFileName = "";
                fullFileName = Path.Combine(uploader.TempPhysicalPath, fileName);
                using (var stream = new FileStream(fullFileName, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
                //将文件路径作为返回值返回 
                var uploadFileName = "";
                uploadFileName = option.DomainImageHost + uploader.TempRelativePath + "/" + fileName;

                //判断图片超过100K，进行压缩
                if (file.Length > 1024 * 100)
                {
                    var ret = true;
                    var fileName_cp = string.Format("{0}_{1}_cp{2}", DateTime.Now.ToString("yyyyMMddhhmmss"), new Random().Next(1000), Path.GetExtension(file.FileName));
                    using (var sm = file.OpenReadStream())
                    {
                        using (Image image = Image.FromStream(sm))
                        {
                            var fullFileName_cp = Path.Combine(uploader.TempPhysicalPath, fileName_cp);
                            ret = ImgTool.Compress(fullFileName, fullFileName_cp, image.Height, image.Width, 50);

                        }
                    }

                    if (!ret)
                    {
                        throw new Exception("图片压缩失败,压缩文件：" + fullFileName);
                    }
                    else
                    {
                        //压缩成功删除临时目录压缩前的图片。
                        try
                        {
                            //将压缩后的新图片，返回给前端
                            var uploadFileName_cp = option.DomainImageHost + uploader.TempRelativePath + "/" + fileName_cp;
                            uploadFileName = uploadFileName_cp.ToForwardSlashPath();
                            System.IO.File.Delete(fullFileName);
                        }
                        catch
                        {
                            throw new Exception("图片删除失败,文件：" + fullFileName);
                        }

                    }
                }

                return uploadFileName;
            }
            catch (Exception ex)
            {
                throw new Exception("上传图片异常：" + ex.ToString());

            }
        }

        public async Task<bool> Upload(List<string> imgs, IFileUploader uploader)
        {
            bool res = true;
            if (imgs.Count > 0)
            {
                foreach (var img in imgs)
                {
                    var _tempFileUrl = Path.Combine(uploader.TempPhysicalPath, Path.GetFileName(img));
                    if (! await UploadImage(uploader.FolderName, _tempFileUrl))
                    {
                        res = false;
                        break;
                    }
                }
            }
            return res;
        }

        public async Task<bool> Upload(string img, IFileUploader uploader)
        {
            bool res = true;
            var _tempFileUrl = Path.Combine(uploader.TempPhysicalPath, Path.GetFileName(img));
            if (!await UploadImage(uploader.FolderName, _tempFileUrl))
            {
                res = false;
            }
            return res;
        }

        /// <summary>
        /// 上传服务
        /// </summary>
        /// <returns></returns>
        private async Task<bool> UploadImage(string uploadType, string path)
        {
            using (WebClient webclient = new WebClient())
            {
                byte[] responseArray = await webclient.UploadFileTaskAsync(option.UploadHost + uploadType, "POST", path);
                string getPath = Encoding.GetEncoding("UTF-8").GetString(responseArray);
                return getPath.Contains("1");
            }

        }
    }
}
